package com.yangyuhao.haowuyoupin.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.yangyuhao.haowuyoupin.R;
import com.yangyuhao.haowuyoupin.BannerAdapter;
import com.yangyuhao.haowuyoupin.ProductListActivity;
import com.yangyuhao.haowuyoupin.adapter.ProductAdapter;
import com.yangyuhao.haowuyoupin.model.ProductResponse;
import com.google.gson.Gson;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

public class HomeFragment extends Fragment {
    private ViewPager2 viewPager;
    private LinearLayout indicatorLayout;
    private BannerAdapter bannerAdapter;
    private ProductAdapter adapter;
    private Handler autoScrollHandler;
    private static final long AUTO_SCROLL_DELAY = 3000; // 3秒
    private boolean isAutoScrolling = false; // 添加标志位
    private ViewPager2.OnPageChangeCallback pageChangeCallback; // 添加成员变量

    private final Runnable autoScrollRunnable = new Runnable() {
        @Override
        public void run() {
            if (viewPager != null && bannerAdapter != null && isAutoScrolling) {
                int nextItem = (viewPager.getCurrentItem() + 1) % bannerAdapter.getItemCount();
                viewPager.setCurrentItem(nextItem, true);
                autoScrollHandler.postDelayed(this, AUTO_SCROLL_DELAY);
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        // 初始化Handler
        autoScrollHandler = new Handler();

        // 初始化轮播图
        viewPager = view.findViewById(R.id.viewPager);
        indicatorLayout = view.findViewById(R.id.indicator);
        setupBanner();

        // 初始化商品列表
        RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getItemViewType(position) == ProductAdapter.TYPE_FOOTER ? 2 : 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);

        try {
            InputStream inputStream = getResources().openRawResource(R.raw.products);
            Reader reader = new InputStreamReader(inputStream, "UTF-8");
            Gson gson = new Gson();
            ProductResponse response = gson.fromJson(reader, ProductResponse.class);
            
            adapter = new ProductAdapter(getContext(), response.getProducts());
            recyclerView.setAdapter(adapter);
            
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                if (layoutManager != null) {
                    int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                    int totalItemCount = layoutManager.getItemCount();
                    if (lastVisibleItem >= totalItemCount - 4) {
                        adapter.showFooter(true);
                    }
                }
            }
        });

        // 设置查看更多点击事件
        view.findViewById(R.id.btn_more).setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ProductListActivity.class);
            startActivity(intent);
        });

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopAutoScroll();
    }

    private void startAutoScroll() {
        if (!isAutoScrolling) {
            isAutoScrolling = true;
            autoScrollHandler.removeCallbacks(autoScrollRunnable); // 先移除之前的回调
            autoScrollHandler.postDelayed(autoScrollRunnable, AUTO_SCROLL_DELAY);
        }
    }

    private void stopAutoScroll() {
        isAutoScrolling = false;
        autoScrollHandler.removeCallbacks(autoScrollRunnable);
    }

    private void setupBanner() {
        bannerAdapter = new BannerAdapter(getContext());
        viewPager.setAdapter(bannerAdapter);
        
        // 添加指示器
        for (int i = 0; i < bannerAdapter.getItemCount(); i++) {
            ImageView dot = new ImageView(getContext());
            dot.setImageResource(R.drawable.dot_normal);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(8, 0, 8, 0);
            indicatorLayout.addView(dot, params);
        }

        // 创建并保存回调对象
        pageChangeCallback = new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                updateIndicator(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    stopAutoScroll();
                } else if (state == ViewPager2.SCROLL_STATE_IDLE) {
                    autoScrollHandler.postDelayed(() -> startAutoScroll(), 500);
                }
            }
        };

        // 注册页面切换监听
        viewPager.registerOnPageChangeCallback(pageChangeCallback);
    }

    private void updateIndicator(int position) {
        for (int i = 0; i < indicatorLayout.getChildCount(); i++) {
            ImageView dot = (ImageView) indicatorLayout.getChildAt(i);
            dot.setImageResource(i == position ? R.drawable.dot_selected : R.drawable.dot_normal);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopAutoScroll();
        if (viewPager != null && pageChangeCallback != null) {
            viewPager.unregisterOnPageChangeCallback(pageChangeCallback);
        }
    }
} 